package gyb.rasa.service.impl;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import gyb.rasa.common.utils.TimeUtils;
import gyb.rasa.entity.Hot;
import gyb.rasa.entity.Ip;
import gyb.rasa.entity.MessageReceived;
import gyb.rasa.entity.User;
import gyb.rasa.entity.vo.EntityQuestions;
import gyb.rasa.entity.vo.HotQuestion;
import gyb.rasa.mapper.HotMapper;
import gyb.rasa.mapper.MessageReceivedMapper;
import gyb.rasa.mapper.UserMapper;
import gyb.rasa.service.HotService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 郜宇博
 * @since 2023-04-20
 */
@Service
public class HotServiceImpl extends ServiceImpl<HotMapper, Hot> implements HotService {

    private final MessageReceivedMapper messageReceivedMapper;
    private final UserMapper userMapper;

    public HotServiceImpl(MessageReceivedMapper messageReceivedMapper, UserMapper userMapper) {
        this.messageReceivedMapper = messageReceivedMapper;
        this.userMapper = userMapper;
    }

    /**
     * 增加热度
     * @param entityName 实体名
     */
    @Override
    public void increaseHot(String entityName) {
        Hot hot = baseMapper.selectOne(new QueryWrapper<Hot>().eq("name", entityName));
        if (!"false".equals(entityName) && !"undefined".equals(entityName)){
            //不存在该实体，新增加一条记录
            if (hot == null){
                baseMapper.insert(new Hot(null,entityName,null));
            }else {
                //向该实体增加一个热度
                hot.setHot(hot.getHot()+1);
                baseMapper.updateById(hot);
            }
        }
    }
    /**
     * 获取热门问答
     *
     * @param countEntity 实体数量
     * @param countQuestion 问答数量
     * @return 热门问答列表
     */
    @Override
    public List<HotQuestion> getHotQuestions(Integer countEntity,Integer countQuestion) {
        // 1.获取热门实体
        List<Hot> hotEntities = getHotEntity(countEntity);
        //创建结果集
        List<HotQuestion> result = new ArrayList<>();
        for (Hot hotEntity : hotEntities) {
            //2. 循环根据热门实体 like出热门问题
            List<MessageReceived> mesReceiveByEntity = getMesReceiveByEntity(hotEntity.getName(), countQuestion);
            //3. 封装hotQuestion
            //将每一个mesReceive转换为HotQuestion
            for (MessageReceived messageReceived : mesReceiveByEntity) {
                HotQuestion hotQuestion = transformToHotQes(messageReceived);
                result.add(hotQuestion);
            }
        }
        return result;
    }
    private String transformRasaContent(String content){
        boolean search = content.contains("search");
        if (search){
            String[] s = content.split("_",2);
            String[] split = s[1].split("\\{");
            System.out.println(Arrays.toString(s));
            String intent = split[0];
            String[] split1 = split[1].split("}");
            //System.out.println(split1[1]);
            String[] split2 = split1[0].split("sure\":\"");
            //System.out.println(split2[1]);
            String[] split3 = split2[1].split("\"");
            String entity = split3[0];
            if ("treat".equals(intent)){
                return entity+"怎么办";
            }
            if ("food".equals(intent)){
                return "在患"+entity+"时饮食应注意什么";
            }
            if ("symptom".equals(intent)){
                return ""+entity+"的症状是什么";
            }
            if ("cause".equals(intent)){
                return entity+"是怎么导致的";
            }
            if ("neopathy".equals(intent)){
                return entity+"的并发症有什么？";
            }
            if("drug".equals(intent)){
                return "得"+entity+"时，应该吃什么药？";
            }
            if("prevention".equals(intent)){
                return "应该如何防治"+entity;
            }
            if ("drug_func".equals(intent)){
                return entity+"可以治疗什么";
            }
            if("disease_treat_time".equals(intent)){
                return entity+"需要治疗多久啊";
            }
            if ("easy_get".equals(intent)){
                return "什么人容易得"+entity;
            }
            if ("disease_dept".equals(intent)){
                return entity+"属于什么科啊?";
            }
            if ("info".equals(intent)){
                return entity+"的介绍";
            }
        }else {
            return content;
        }
        return content;
    }

    @Override
    public HotQuestion transformToHotQes(MessageReceived messageReceived) {
        HotQuestion hotQuestion = new HotQuestion();
        //mid
        hotQuestion.setMid(messageReceived.getMid());
        User user = userMapper.selectById(messageReceived.getFromUserId());
        //username
        hotQuestion.setFromUserName(user.getUsername());
        //session_id
        hotQuestion.setSessionId(messageReceived.getSessionId());
        //content
        String transformContent = transformRasaContent(messageReceived.getContent());
        hotQuestion.setContent(transformContent);
        //when
        String when = TimeUtils.format(messageReceived.getWhen());
        hotQuestion.setWhen(when);
        //ip
        hotQuestion.setIpAddress(messageReceived.getIpAddress());
        //response
        String response = messageReceived.getResponse();
        //entity
        hotQuestion.setEntity(messageReceived.getEntity());
        //good
        hotQuestion.setGood(messageReceived.getGood());

        //处理空response
        if (response == null || StringUtils.isEmpty(response) || "Null".equals(response)){
            ArrayList<String> emptyResponse = new ArrayList<>();
            emptyResponse.add("结果丟失啦，请查看其它问答吧~");
            hotQuestion.setResponse(emptyResponse);
        }else {
            JSONArray objects = null;
            try {
                objects = JSONUtil.parseArray(response);
            } catch (Exception e) {
                ArrayList<String> list = new ArrayList<>();
                list.add(response);
                hotQuestion.setResponse(list);
                return hotQuestion;
            }
            ArrayList<String> list = (ArrayList<String>) objects.toList(String.class);
            hotQuestion.setResponse(list);
        }

        return hotQuestion;
    }

    /**
     * 分页获取Hot
     *
     * @param current 当前页
     * @param limit   最大数量
     * @return hotList
     */
    @Override
    public IPage<Hot> getHotByPage(Long current, Long limit) {
        IPage<Hot> page = new Page<>(current,limit);
        IPage<Hot> hotIPage = this.page(page,new QueryWrapper<Hot>().orderByDesc("hot"));
        return hotIPage;
    }

    private List<MessageReceived> getMesReceiveByEntity(String entity, Integer countQuestion){
        QueryWrapper<MessageReceived> queryWrapper = new QueryWrapper<MessageReceived>()
                .like(true, "content", entity)
                .groupBy("content")
                .orderByDesc("mid")
                .last("limit "+countQuestion);
        return messageReceivedMapper.selectList(queryWrapper);
    }

    /**
     * 获取热门实体
     *
     * @param count 数量
     * @return 热门实体列表
     */
    @Override
    public List<Hot> getHotEntity(Integer count) {
        QueryWrapper<Hot> queryWrapper = new QueryWrapper<Hot>()
                .select("name","hot")
                .orderByDesc("hot")
                .ne("name","false")
                .ne("name","undefined")
                .last("limit " + count);
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 根据实体名获取热门问答
     *
     * @param entitys        实体名
     * @param countQuestion 问答数量
     * @return 热门实体、问答列表
     */
    @Override
    public Map<String, List<HotQuestion>> getHotQuestionsByEntity(String entitys, Integer countQuestion) {
        //创建结果集
        Map<String, List<HotQuestion>> result = new HashMap<>();
        String[] entityArray = entitys.split(",");
        for (String entity : entityArray) {
            //创建每一个entity的list结果
            List<HotQuestion> hotQuestionList = new ArrayList<>();
            //获取MessageReceive格式的结果list
            List<MessageReceived> mesReceiveByEntity = getMesReceiveByEntity(entity, countQuestion);
            for (MessageReceived messageReceived : mesReceiveByEntity) {
                //将MessageReceived格式转换为HotQuestion
                HotQuestion hotQuestion = transformToHotQes(messageReceived);
                hotQuestionList.add(hotQuestion);
            }
            result.put(entity,hotQuestionList);
        }
        return result;
    }

    /**
     * 根据单个实体名获取热门问答
     *
     * @param entity        实体名
     * @param countQuestion 问答数量
     * @return 热门实体、问答列表
     */
    @Override
    public EntityQuestions getHotQuestionsBySingleEntity(String entity, Integer countQuestion) {
        //创建一个entity的list结果
        List<HotQuestion> hotQuestionList = new ArrayList<>();
        //获取MessageReceive格式的结果list
        List<MessageReceived> mesReceiveByEntity = getMesReceiveByEntity(entity, countQuestion);
        for (MessageReceived messageReceived : mesReceiveByEntity) {
            //将MessageReceived格式转换为HotQuestion
            HotQuestion hotQuestion = transformToHotQes(messageReceived);
            hotQuestionList.add(hotQuestion);
        }
        EntityQuestions entityQuestions = new EntityQuestions();
        entityQuestions.setEntity(entity);
        entityQuestions.setQuestions(hotQuestionList);
        return entityQuestions;
    }
}
